#include "DrawObject.h"
#include "SpriteList.h"
#include <GL/glfw.h>
#include <iostream>

DrawObject::DrawObject(int tx, int ty, int tz, int tid)
{
	x = tx;
	y = ty;
	z = tz;
	id = tid;
	angle = 0.0;
	escale = 100.0;
	flipx = false;
	flipy = false;
}

DrawObject::DrawObject(int tx, int ty, int tz, int tid, float tangle)
{
	x = tx;
	y = ty;
	z = tz;
	id = tid;
	angle = tangle;
	escale = 100.0;
	flipx = false;
	flipy = false;
}

DrawObject::DrawObject(int tx, int ty, int tz, int tid, float tangle,float tescale, bool tflipx, bool tflipy)
{
	x = tx;
	y = ty;
	z = tz;
	id = tid;
	angle = tangle;
	escale = tescale;
	flipx = tflipx;
	flipy = tflipy;
}

void DrawObject::Draw(void)
{	
	int tex,w,h;
	int center_x,center_y;
	float xini,yini,xend,yend;

	tex = SPRITELIST_GetTexture(id);
	w = SPRITELIST_GetWidth(id);
	h = SPRITELIST_GetHeight(id);

	w *= escale;
	h *= escale;

	w/= 100.0;
	h/= 100.0;

    glAlphaFunc(GL_GREATER,0.1f);
	glEnable(GL_ALPHA_TEST);

	glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, tex);
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );

	center_x = x + w/2 ;
	center_y = y + h/2 ;

	if(flipx)
	{
		xini = 1.0f;
		xend = 0.0f;
	}
	else
	{
		xini = 0.0f;
		xend = 1.0f;
	}

	if(flipy)
	{
		yini = 1.0f;
		yend = 0.0f;
	}
	else
	{
		yini = 0.0f;
		yend = 1.0f;
	}

	glPushMatrix();

		glTranslatef( (GLfloat) center_x, (GLfloat) center_y, 0 );
		glRotatef( angle , 0, 0, 1 );
		glTranslatef( - (GLfloat) center_x, - (GLfloat) center_y, 0 );

			glBegin(GL_QUADS);
				glTexCoord2f( xend, yend); glVertex2i( x + w , y + h ); 
				glTexCoord2f( xini, yend); glVertex2i( x     , y + h ); 
				glTexCoord2f( xini, yini); glVertex2i( x     , y  ); 
				glTexCoord2f( xend, yini); glVertex2i( x + w    , y ); 
			glEnd();

	glPopMatrix();

};